/*
 * @Description: global router guards
 * @Autor: dongjunhua
 * @Date: 2020-12-17 13:02:54
 * @LastEditors: dongjunhua
 * @LastEditTime: 2022-04-14 09:39:49
 */

import NProgress from 'nprogress'; // progress bar
import 'nprogress/nprogress.css'; // progress bar style
import store from '@/store';

// NProgress Configuration
NProgress.configure({ showSpinner: false });

// not authenticated
// 未认证状态白名单
const whiteListLv1 = ['/login', '/auth-redirect'];
// authenticated
// 已认证状态白名单
const whiteListLv2 = [
  '/login',
  '/auth-redirect',
  '/i',
  '/401',
  '/404',
  '/404',
  '/i/workplace',
  '/workplace'
];

const before = async (to, from, next) => {
  // console.log('into guard', to.name);
  // start progress bar
  NProgress.start();
  // if (!to.name) {
  //   next({ path: '/404', replace: true });
  // }

  if (store.state.subject.initialized) {
    // try to get persistence data from storage when subject is initialized, e.g., refresh
    // 当会话处于初始化状态时尝试从storage中恢复
    await store.dispatch('subject/recovery');
    next({ ...to, replace: true });
  } else if (
    store.state.subject.isAuthenticated &&
    store.state.subject.isPermitted
  ) {
    // authenticated and permitted
    // 已认证和授权
    if (whiteListLv1.includes(to.path)) {
      // when current path in whitelist
      // 当前路由属于白名单
      if (to.query.redirect_uri) {
        next();
        NProgress.done();
        const { sso_logout, ...query } = to.query;
        if (sso_logout === 'true') {
          store.dispatch('subject/logout', { query });
        } else {
          window.location.href = `${to.query.redirect_uri}?code=${store.state.subject.token}`;
        }
      } else {
        next({ path: '/i', replace: true });
      }
    } else {
      // check for permission of current path when not in whitelist
      // 当前路由不属于白名单时检查权限
      const hasPermission = await store.dispatch('subject/checkPermission', {
        path: to.path,
        whiteList: whiteListLv2
      });
      if (hasPermission) {
        next();
        NProgress.done();
        // document.title = to.name;
      } else {
        next({ path: '/401', replace: true });
      }
    }
  } else {
    // not authenticated
    // 未认证
    NProgress.done();
    if (whiteListLv1.includes(to.path)) {
      next();
    } else {
      const redirect = await store.dispatch('subject/logout', {
        doRouterPush: false
      });
      next(redirect);
    }
  }
};

const after = () => {
  // 清空keep-alive排除路由
  store.dispatch('app/setDestoryRoute', null);
  // end progress bar
  NProgress.done();
};

export { before, after };
